/**------------------------------------------------------------
 *
 * Copyright © 2014 rubbervalley. All rights reserved.
 *
 * @Title: UploadFile.java
 * @Package: com.rubbervalley.rvgrip.util
 * @Description: 文件上传处理
 * @author: zl
 * @date: 下午6:08:58
 * @version: V1.0
 * 
 ------------------------------------------------------------*/
package com.rubbervalley.uyo.util;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.rubbervalley.platform.business.PlatUploadfileService;
import com.rubbervalley.platform.domain.PlatUploadfile;
import com.rubbervalley.uyo.domain.UploadBean;

public class UploadFile {
	public static Integer UPLOAD_FILE = 1;// 上传文件
	public static Integer UPLOAD_IMAGE = 2;// 上传图片
	int OutputWidth = 150; // 默认输出图片宽
	int OutputHeight = 150; // 默认输出图片高
	boolean proportion = true; // 是否等比缩放标记(默认为等比缩放)
	@Autowired
	private PlatUploadfileService platUploadfileService;

	private static final Logger logger = LoggerFactory
			.getLogger("************");

	/**
	 * 处理文件信息并返回
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public UploadBean updateFile(CommonsMultipartFile imgFile,
			HttpServletRequest request, String realpath, Integer type)
			throws IOException
	{
		String iconUrl = "";
		PlatUploadfile platUploadfile = null;
		if (type == UploadFile.UPLOAD_FILE) {
			platUploadfile = saveFile(imgFile, request, realpath);
		} else if (type == UploadFile.UPLOAD_IMAGE) {
			platUploadfile = saveFile(imgFile, request, realpath);
		}
		iconUrl = platUploadfile.getUrl();
		// 返回json格式图片信息
		iconUrl = iconUrl.replace("\\\\", File.separator);
		UploadBean bean = new UploadBean();
		bean.setOriginal(imgFile.getOriginalFilename());
		bean.setUrl(iconUrl);
		bean.setFileType(platUploadfile.getId());
		bean.setState("SUCCESS");
		bean.setId(platUploadfile.getId());
		return bean;
	}

	/**
	 * 保存文件
	 * 
	 * @param file
	 */
	private PlatUploadfile saveFile(CommonsMultipartFile imgFile,
			HttpServletRequest request, String realpath)
	{
		if (imgFile != null && !imgFile.isEmpty()) {

			ServletContext context = request.getSession().getServletContext();
			String path = context.getRealPath(File.separator + realpath);
			String resFileName = imgFile.getOriginalFilename();
			logger.debug(resFileName);
			// 保存的文件名
			String fileName = uuIdName(resFileName);

			File targetFile = new File(path, fileName);
			String urlPath = realpath + fileName;

			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}

			PlatUploadfile platUploadfile = new PlatUploadfile();
			// 将文件信息保存到数据库
			platUploadfile.setType(this.getExtensionName(resFileName));
			platUploadfile.setNewName(fileName);
			platUploadfile.setOriginalName(imgFile.getOriginalFilename());
			platUploadfile.setDirectory(targetFile.getAbsolutePath());
			platUploadfile.setSize((Long) imgFile.getSize());
			platUploadfile.setUrl(urlPath);
			platUploadfileService.insert(platUploadfile);
			try {
				imgFile.transferTo(targetFile);
			} catch (Exception e) {
				logger.error("saveFile", e);
			}
			return platUploadfile;
		}
		return null;

	}

	/**
	 * 保存图片，等比缩放（未使用）
	 * 
	 * @param file
	 * @throws IOException
	 */
	@SuppressWarnings("unused")
	private PlatUploadfile saveImage(CommonsMultipartFile imgFile,
			HttpServletRequest request, String realpath) throws IOException
	{
		if (imgFile != null && !imgFile.isEmpty()) {

			BufferedImage bufferedImage = ImageIO
					.read(imgFile.getInputStream());
			int new_w;
			int new_h;
			if (this.proportion == true) { // 判断是否是等比缩放.
				// 为等比缩放计算输出的图片宽度及高度
				double rate1 = ((double) bufferedImage.getWidth(null))
						/ (double) OutputWidth + 0.1;
				double rate2 = ((double) bufferedImage.getHeight(null))
						/ (double) OutputHeight + 0.1;
				double rate = rate1 > rate2 ? rate1 : rate2;
				new_w = (int) (((double) bufferedImage.getWidth(null)) / rate);
				new_h = (int) (((double) bufferedImage.getHeight(null)) / rate);
			} else {
				new_w = OutputWidth; // 输出的图片宽度
				new_h = OutputHeight; // 输出的图片高度
			}

			// 根据ComminsMutilpartFile得到文件输入流，BufferedImage读取这个输入流得到bufferedImage实例
			BufferedImage bufferedImage1 = new BufferedImage(new_w, new_h,
					BufferedImage.TYPE_INT_BGR);

			// 得到一个一个100*100的Image对象
			Image image = bufferedImage.getScaledInstance(new_w, new_h,
					BufferedImage.SCALE_DEFAULT);

			Graphics g = bufferedImage1.createGraphics();
			g.setColor(Color.white);
			g.fillRect(0, 0, new_w, new_h);
			g.drawImage(image, 0, 0, new_w, new_h, null);
			g.dispose();

			ServletContext context = request.getSession().getServletContext();
			String path = context.getRealPath(File.separator + realpath);
			String resFileName = imgFile.getOriginalFilename();
			logger.debug("OriginalFilename=" + resFileName);
			// 保存的文件名
			String fileName = uuIdName(resFileName);

			File targetFile = new File(path, fileName);
			String urlPath = realpath + fileName;

			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}

			PlatUploadfile platUploadfile = new PlatUploadfile();
			// 将文件信息保存到数据库
			platUploadfile.setType(this.getExtensionName(resFileName));
			platUploadfile.setNewName(fileName);
			platUploadfile.setOriginalName(imgFile.getOriginalFilename());
			platUploadfile.setDirectory(targetFile.getAbsolutePath());
			platUploadfile.setSize((Long) imgFile.getSize());
			platUploadfile.setUrl(urlPath);
			platUploadfileService.insert(platUploadfile);
			try {
				ImageIO.write(bufferedImage1,
						this.getExtensionName(resFileName), targetFile);
			} catch (Exception e) {
				logger.error("saveFile", e);
			}
			return platUploadfile;
		}
		return null;

	}

	/**
	 * 生成唯一的文件名称
	 * 
	 * @param name
	 * @return
	 */
	private String uuIdName(String name)
	{
		UUID uuid = UUID.randomUUID();

		String uustr = uuid.toString();

		if (name.indexOf(".") != -1) {
			uustr += name.substring(name.lastIndexOf("."));
		}
		return uustr;
	}

	/**
	 * Java文件操作 获取文件扩展名
	 */
	public String getExtensionName(String filename)
	{
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}

	/**
	 * 删除原文件
	 * 
	 * @param file
	 */
	public boolean deleteFile(String urlPath, HttpServletRequest request)
	{
		if (urlPath == null || urlPath.isEmpty())
			return false;

		ServletContext context = request.getSession().getServletContext();
		String path = context.getRealPath("/") + urlPath;
		path = path.replace("/", File.pathSeparator);
		File file = new File(path);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			return true;
		}
		return false;
	}

}
